package com.bsg.upm.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.check.CheckResult;
import com.bsg.upm.check.DictCheck;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.dto.DictDto;
import com.bsg.upm.entity.DictEntity;
import com.bsg.upm.entity.DictTypeEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * 字典类型业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class DictService extends BaseService {

	@Resource
	private DictCheck dictCheck;

	/**
	 * 字典类型项查询
	 * 
	 * @param dictTypeCode
	 *            字典类型代码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(String dictTypeCode) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// 从缓存中获取字典类型
			List<DictTypeEntity> dictTypes = dictTypeCache.listDictTypeFromCache();
			for (DictTypeEntity dictType : dictTypes) {
				if (dictType.getCode().equals(dictTypeCode)) {
					List<DictEntity> dicts = dictType.getDicts();
					for (DictEntity dict : dicts) {
						DictDto dto = new DictDto();
						dto.setCode(dict.getCode());
						dto.setName(dict.getName());
						dto.setSequence(dict.getSequence());
						results.add(dto);
					}
					break;
				}
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("字典类型项查询异常", e);
			throw new APIException("字典类型项查询异常:" + e.getMessage());
		}
	}

	/**
	 * 获取字典类型项列表
	 * 
	 * @param dictTypeCode
	 *            字典类型代码
	 * @param code
	 *            字典代码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson get(String dictTypeCode, String code) throws APIException {
		try {
			// 从缓存中获取指定字典类型代码和字典代码的字典类型项
			DictEntity dict = dictTypeCache.getDictFromCache(dictTypeCode, code);
			if (dict == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该字典类型项不存在");
			}

			DictDto dto = new DictDto();
			dto.setCode(dict.getCode());
			dto.setName(dict.getName());
			dto.setSequence(dict.getSequence());

			return RespJsonFactory.buildOK(dto);
		} catch (Exception e) {
			logger.error("字典类型项查询异常", e);
			throw new APIException("字典类型项查询异常:" + e.getMessage());
		}
	}

	/**
	 * 字典类型项新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 字典类型项新增检查
			CheckResult chkRS = dictCheck.checkSave(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			DictEntity dict = new DictEntity();
			dict.setDictTypeCode((String) paramMap.get("dictTypeCode"));
			dict.setCode(StringUtils.trim((String) paramMap.get("code")));
			dict.setName(StringUtils.trim((String) paramMap.get("name")));
			dict.setSequence((Integer) paramMap.get("sequence"));
			dictTypeCache.saveDict(dict);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_DICT, operateAcion, dict.getCode(), dict.getName());

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("字典类型项" + operateAcionText + "异常", e);
			throw new APIException("字典类型项" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 字典类型项编辑
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson update(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_UPDATE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 字典类型项编辑检查
			CheckResult chkRS = dictCheck.checkUpdate(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			DictEntity dict = new DictEntity();
			dict.setDictTypeCode((String) paramMap.get("dictTypeCode"));
			dict.setCode(StringUtils.trim((String) paramMap.get("code")));
			dict.setName(StringUtils.trim((String) paramMap.get("name")));
			dict.setSequence((Integer) paramMap.get("sequence"));
			dictTypeCache.updateDict(dict);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_DICT, operateAcion, dict.getCode(), dict.getName());

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("字典类型项" + operateAcionText + "异常", e);
			throw new APIException("字典类型项" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 字典类型项删除
	 * 
	 * @param dictTypeCode
	 *            字典类型代码
	 * @param code
	 *            字典代码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String dictTypeCode, String dictCode) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的字典类型项
			DictEntity dict = dictDao.getByDictTypeCodeAndDictCode(dictTypeCode, dictCode);

			// 字典类型项删除检查
			CheckResult chkRS = dictCheck.checkRemove(dict);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			dictTypeCache.removeDict(dict);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_DICT, operateAcion, dict.getCode(), dict.getName());

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("字典类型项" + operateAcionText + "异常", e);
			throw new APIException("字典类型项" + operateAcionText + "异常" + e.getMessage());
		}
	}
}
